
# controllers/main_function.py
from PySide6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QPushButton, 
                             QStackedWidget)
from functools import partial
from core.event_bus import EventBus
from core.page_manager import PageManager
# 导入视图
from views.home_views import HomeMain, HomeProfile, HomeFeed
from views.health_views import HealthPage
from views.messages_views import MessagesPage
from views.settings_views import (SettingsMain, SettingsAccount, 
                                SettingsNotification, SettingsWiFi)
from controllers.home_controller import HomeController  # 导入首页控制器

class MainFunctionWidget(QWidget):
    def __init__(self, event_bus, page_manager):
        super().__init__()
        # 移除QWidget的窗口标题和几何设置，由父容器控制
        
        # 初始化核心组件
        self.event_bus = event_bus
        self.page_manager = page_manager
        self.event_bus.switch_main_page.connect(self.switch_main_page)
        
        # 初始化UI
        self.init_ui()
        self.create_sub_stacks()  # 先注册所有页面

        # 初始化首页控制器（在页面注册后）
        self.home_controller = HomeController(self.event_bus)

        # 最后发送显示首页的事件
        self.event_bus.switch_main_page.emit("home")
    
    def init_ui(self):
        """初始化主窗口UI（侧边栏+主栈）"""
        self.main_widget = QWidget()
        self.main_layout = QHBoxLayout(self.main_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)
        
        # 创建侧边栏
        self.create_sidebar()
        
        # 创建主页面栈
        self.main_stack = QStackedWidget()
        self.main_layout.addWidget(self.main_stack, 4)
        
        # 将main_widget设置为当前部件的布局
        self.setLayout(QVBoxLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.main_widget)
    
    def create_sidebar(self):
        """创建侧边栏导航"""
        sidebar = QWidget()
        sidebar.setStyleSheet("background-color: #2c3e50; color: white;")
        sidebar_layout = QVBoxLayout(sidebar)
        sidebar_layout.setContentsMargins(0, 30, 0, 0)
        sidebar_layout.setSpacing(0)
        self.main_layout.addWidget(sidebar, 1)
        
        # 导航按钮
        nav_items = [("首页", "home"), ("健康", "health"), 
                    ("消息", "messages"), ("设置", "settings")]
        for text, page_id in nav_items:
            btn = QPushButton(text)
            btn.setStyleSheet("""
                QPushButton { color: white; background-color: #2c3e50; border: none;
                              padding: 15px; text-align: left; font-size: 14px; }
                QPushButton:hover { background-color: #34495e; }
                QPushButton:pressed, QPushButton:checked { background-color: #1abc9c; }
            """)
            btn.setCheckable(True)
            btn.clicked.connect(partial(self.on_nav_clicked, page_id))
            sidebar_layout.addWidget(btn)
            setattr(self, f"{page_id}_btn", btn)
        
        sidebar_layout.addStretch()
    
    def on_nav_clicked(self, page_id):
        """侧边栏按钮点击事件"""
        self.event_bus.switch_main_page.emit(page_id)
    
    def create_sub_stacks(self):
        """注册所有页面到管理器"""
        # 首页子栈
        home_stack = QStackedWidget()
        self.page_manager.register_main_page("home", home_stack)
        self.page_manager.register_sub_stack("home", home_stack)
        self.page_manager.register_sub_page("/home/main", "home", HomeMain(self.event_bus))
        self.page_manager.register_sub_page("/home/profile", "home", HomeProfile(self.event_bus))
        self.page_manager.register_sub_page("/home/feed", "home", HomeFeed(self.event_bus))
        
        # 健康页面
        health_page = HealthPage()
        self.page_manager.register_main_page("health", health_page)
        
        # 消息页面
        messages_page = MessagesPage()
        self.page_manager.register_main_page("messages", messages_page)
        
        # 设置子栈
        settings_stack = QStackedWidget()
        self.page_manager.register_main_page("settings", settings_stack)
        self.page_manager.register_sub_stack("settings", settings_stack)
        self.page_manager.register_sub_page("/settings/main", "settings", SettingsMain(self.event_bus))
        self.page_manager.register_sub_page("/settings/account", "settings", SettingsAccount(self.event_bus))
        self.page_manager.register_sub_page("/settings/notification", "settings", SettingsNotification(self.event_bus))
        self.page_manager.register_sub_page("/settings/wifi", "settings", SettingsWiFi(self.event_bus))
        
        # 添加主页面到主栈
        for page in self.page_manager.main_pages.values():
            self.main_stack.addWidget(page)
    
    def switch_main_page(self, page_id):
        """切换主页面（保留子页面状态）"""
        # 更新按钮选中状态
        for pid in self.page_manager.main_pages.keys():
            btn = getattr(self, f"{pid}_btn", None)
            if btn:
                btn.setChecked(pid == page_id)
        
        # 切换主栈
        if page_id in self.page_manager.main_pages:
            index = self.main_stack.indexOf(self.page_manager.main_pages[page_id])
            self.main_stack.setCurrentIndex(index)

            # 如果是有子栈的页面，默认显示其主页面，注销以下代码即可实现保留子页面状态
            if page_id in self.page_manager.sub_stacks:
                if page_id == "home":
                    self.event_bus.switch_sub_page.emit("/home/main")
                elif page_id == "settings":
                    self.event_bus.switch_sub_page.emit("/settings/main")
